#!/usr/bin/python
# -*- coding: utf-8 -*-
# encoding: utf-8
#客户端调用，用于查看API返回结果

from OkcoinSpotAPI import OKCoinSpot
import config
import time
import json
import traceback

#初始化apikey，secretkey,url
apikey = config.API_KEY
secretkey = config.SECRET_TOKEN
okcoinRESTURL = 'www.okex.com'

#现货API
okcoinSpot = OKCoinSpot(okcoinRESTURL,apikey,secretkey)

# print (u' 现货行情 ')
# print (okcoinSpot.ticker('btc_usdt'))

# print (u' 用户现货账户信息 ')
# print (okcoinSpot.userinfo())

#先获取钱包账户可用币数，
#然后划转到现货账户，
#然后获取当前挂单，撤销所有挂单，
#获取当前价格，获取现货账户币数，挂单，
#以上操作用try catch包起来，若失败重新执行，最多连续执行3次

#获取钱包账户btc
def get_wallet_btc_amount():
    userWalletInfo = okcoinSpot.userWalletInfo()
    free_btc = float(json.loads(userWalletInfo)['info']['funds']['free']['btc'])
    if free_btc < 0.001:
        free_btc = 0
    else:
        free_btc = int(free_btc*1000)/1000
    return free_btc

#资金划转
def transfer(amount):
    okcoinSpot.funds_transfer(amount)
    print('资金划转成功')

#取消所有订单
def cancelAllOrder():
    orders = json.loads(okcoinSpot.orderinfo())['orders']
    ordersId = []
    if orders:
        for order in orders:
            ordersId.append(order['order_id'])
    
    if ordersId:
        for orderId in ordersId:
            okcoinSpot.cancelOrder(orderId)
        print('已取消所有订单')
        time.sleep(5) # 以免服务器没反应过来，导致后面的sell操作失败
    else:
        print('暂无挂单，不用取消订单')

#获取现货账户btc
def get_btc_amount():
    userinfo = okcoinSpot.userinfo()
    free_btc = float(json.loads(userinfo)['info']['funds']['free']['btc'])
    if free_btc < 0.001:
        free_btc = 0
    else:
        free_btc = int(free_btc*1000)/1000
    return free_btc

#卖出
def sell(amount):
    if amount != 0:
        # 在python中，键名跟键值用双引号引起来的是json字符串，单引号的是dict
        result = okcoinSpot.ticker('btc_usdt')
        last_price = float(result['ticker']['last']) * (1+config.PLUS)
        okcoinSpot.trade('btc_usdt', 'sell', int(last_price*100)/100, amount)
        print('已挂单')
    else:
        print('可卖数量为零')


def onTick(n):
    if n>3:
        print('-----此轮操作的多次尝试均失败，等待下一轮-----')
        return
    
    try:
        wallet_btc_amount = get_wallet_btc_amount()
        if wallet_btc_amount > 0:
            transfer(wallet_btc_amount)
        cancelAllOrder()
        sell(get_btc_amount())
    except:
        traceback.print_exc()
        print('操作失败，正在重试')
        time.sleep(5)
        onTick(n+1)


def main():
    while True:
        print('-----开始操作-----')
        onTick(0)
        print('-----操作完毕-----')
        time.sleep(config.TickInterval)


if __name__ == '__main__':
    main()

